package main

import (
	"errors"
	"fmt"
	"github.com/go-redis/redis"
)

var rdb *redis.Client

func initClient() (err error) {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	_, err = rdb.Ping().Result()
	return err
}
func main() {
	if err := initClient(); err != nil {
		fmt.Printf("redis连接失败，err:%v\n", err)
		return
	}
	fmt.Printf("redis连接成功\n")
	defer rdb.Close()
	redisExample()
	hgetDemo()
}

func redisExample() {
	err := rdb.Set("score", 100, 0).Err()
	if err != nil {
		fmt.Printf("set score failed, err:%v\n", err)
		return
	}

	val, err := rdb.Get("score").Result()
	if err != nil {
		fmt.Printf("get score failed, err:%v\n", err)
		return
	}
	fmt.Printf("score的值为：%v\n", val)

	val2, err := rdb.Get("name").Result()
	if errors.Is(err, redis.Nil) {
		fmt.Printf("name does not exist\n")
	} else if err != nil {
		fmt.Printf("get name failed, err:%v\n", err)
		return
	} else {
		fmt.Printf("name的值为：%v\n", val2)
	}
}

func hgetDemo() {
	v, err := rdb.HGetAll("user").Result()
	if err != nil {
		fmt.Printf("hgetall failed, err:%v\n", err)
		return
	}
	fmt.Printf("hgetall result:%v\n", v)

	v2 := rdb.HMGet("user", "name", "age").Val()
	fmt.Printf("hmget result:%v\n", v2)

	v3 := rdb.HGet("user", "name").Val()
	fmt.Printf("hget result:%v\n", v3)
}
